package list;

/**
 * title:   将两个升序链表合并为一个新的升序链表并返回
 */
public class MergeTwoLists {
    public static void main(String[] args) {

        int[] n1 = new int[]{1, 2, 4};
        int[] n2 = new int[]{1, 3, 4};
        ListNode l1 = ListUtil.getListFromArray(n1);
        ListNode l2 = ListUtil.getListFromArray(n2);
        ListNode res = mergeTwoLists(l1, l2);
        ListUtil.listToString(res);
    }

    public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode pre = new ListNode(0);
        ListNode cur = pre;

        while (l1 != null && l2 != null) {
            if (l1.val < l2.val) {
                cur.next = l1;
                l1 = l1.next;
            } else {
                cur.next = l2;
                l2 = l2.next;
            }
            cur = cur.next;
        }
        if (l1 == null) {
            cur.next = l2;
        }
        if (l2 == null) {
            cur.next = l1;
        }
        return pre.next;
    }
}
